package com.wangy.security;


import java.io.UnsupportedEncodingException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

public class MD5 {
	
	private static char hexDigits[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8',
		'9', 'a', 'b', 'c', 'd', 'e', 'f' };

	public static String md5(byte[] buff) {
		try {
			return byteToHexString(MessageDigest.getInstance("MD5").digest(buff));
		} catch (NoSuchAlgorithmException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	public static String md5(String message) {
		try {
			return md5(message.getBytes("UTF-8"));
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		}
		return null;
	}
	
	private static String byteToHexString(byte[] buff) {
		char str[] = new char[16 * 2]; 
		int k = 0;
		for (int i = 0; i < 16; i++) {
			byte byte0 = buff[i];
			str[k++] = hexDigits[byte0 >>> 4 & 0xf];
			str[k++] = hexDigits[byte0 & 0xf];
		}
		return new String(str);
	}
	
}

